有些特殊的HTTP請求,需要額外指定參數才能送出。
import requests
url = "http://httpbin.org/cookies"
cookies = dict(name='Roro Chen')
r = requests.get(url, cookies=cookies)
print(r.text)
import requests
try:
r = requests.get("http://www.google.com", timeout=0.01)
print(r.text)
except requests.exceptions.Timeout as ex:
print("錯誤: HTTP請求已經超過時間...\n" + str(ex))
import requests
url = 'http://www.google.com/404'
try:
r = requests.get(url, timeout=3)
r.raise_for_status()
except requests.exceptions.RequestException as ex1:
print("Http請求錯誤: " + str(ex1))
except requests.exceptions.HTTPError as ex2:
print("Http回應錯誤: " + str(ex2))
except requests.exceptions.ConnectionError as ex3:
print("網路連線錯誤: " + str(ex3))
except requests.exceptions.Timeout as ex4:
print("Timeout錯誤: " + str(ex4))
import requests
r = requests.get("https://rouan0903.github.io/")
r.encoding = "utf-8"
fp = open("Hw1.txt", "w", encoding="utf8")
fp.write(r.text)
print("寫入檔案Hw1.txt...")
fp.close()
(2)讀取檔案的全部內容
fp = open("Hw1.txt", "r", encoding="utf8")
str = fp.read()
print("檔案內容:")
print(str)